package com.jic.member.advice;

import com.alibaba.fastjson.JSONObject;
import com.jic.common.base.vo.RestResult;
import com.jic.member.exception.BussinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice(annotations = {Controller.class, RestController.class}, basePackages = {
        "com.jic.member.controller"})
@Slf4j
public class WebControllerAdvice {

    @ExceptionHandler(BussinessException.class)
    public void handleException(HttpServletResponse response, BussinessException throwable) throws IOException {
        RestResult res = RestResult.error(throwable.getRespCode(), throwable.getMessage());
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        log.error("invoke fail: url={}", getPath(request), throwable);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(JSONObject.toJSONString(res));
        response.getWriter().flush();
    }

    private String getPath(HttpServletRequest request) {
        return request.getRequestURI().substring(request.getContextPath().length());
    }
}